/*script.newObject("test", "TestPlug");
test.sayHello("works?");
test.sayGoodbye("works!!");
script.deleteObject("test");*/
//"D:\\snapshot20080505011346.jpg.bmp"
//eval("(" + authreq.getContents() + ")")

script.setStatusText("Authentication...");
script.newObject("authreq", "WebRequest");
authreq.requestFinished.connect(authRequestFinished);
authreq.get("http://rghost.net/multiple/upload_host");

function authRequestFinished() {
	var resp = JSON.parse(authreq.getContents()); //parse JSON answer
	var uphost = resp["upload_host"];
	var authcode = resp["authenticity_token"];
	if(authcode.length && uphost.length) {
		script.setStatusText("Uploading file " + script.filepath());
		script.newObject("data", "PostData");
		data.setContentType(data.Enum.CT_FormData);
		data.appendField("authenticity_token", authcode)
		data.setValuesCharset(data.Enum.CS_UTF8); //encode filename in utf-8
		data.appendFile("file", script.filepath(), "application/octet-stream");
		script.newObject("request", "Request");
		request.setUrl("http://" + uphost + "/files");
		request.setHeader("Cookie", authreq.getHeader("Set-Cookie"));
		script.newObject("uploadreq", "WebRequest");
		uploadreq.requestFinished.connect(uploadRequestFinished);
		uploadreq.post(request, data);
		script.deleteObject("request");
	} else script.failed("Can't get auth information from server");
	script.deleteObject("authreq");
}

function uploadRequestFinished() {
	script.newObject("res", "Result");
	res.appendUrl(uploadreq.getUrl(), "File uploaded to rghost at");
	script.finished(res);
	script.deleteObject("res");
	
	//script.succeeded("Everything is ok: " + uploadreq.getUrl());
	script.deleteObject("data");
	script.deleteObject("uploadreq");
}